package com.cy.aircompressor.main.welcome;

import android.text.TextUtils;

import androidx.lifecycle.Observer;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.ActivitySplashBinding;
import com.cy.aircompressor.entity.system.UserInfo;
import com.cy.aircompressor.main.home.MainActivity;
import com.cy.aircompressor.main.welcome.viewmodel.WelcomeViewModel;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.net.model.base.Resource;
import com.net.model.base.activity.BaseVMActivity;

public class SplashActivity extends BaseVMActivity<ActivitySplashBinding, WelcomeViewModel> {

    @Override
    protected ActivitySplashBinding getViewBinding() {
        return ActivitySplashBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        if (AirConfig.get().isLoginFlag()) {
            MainActivity.start(mContext);
        } else {
            if (!TextUtils.isEmpty(SPManager.getPassWord()) &&
                    !TextUtils.isEmpty(SPManager.getUserName()) &&
                    SPManager.getRememberPassword()) {
                mViewModel.login(SPManager.getUserName(), SPManager.getPassWord());
            } else {
                LoginActivity.start(mContext);
                finish();
            }
        }
    }

    @Override
    protected void dataChange() {
        mViewModel.getLoginObservable().observe(this, boserver -> {
            boserver.handler(new OnCallback<String>(true,false) {
                @Override
                public void onSuccess(String data) {
                    SPManager.setToken(data);
                    AirConfig.get().updateLoginFlag(true);
                    mViewModel.currentUserInfo();
                }

                @Override
                public void onFailure(Integer code, String message) {
                    super.onFailure(code, message);
                    ToastUtil.show(message);
                    LoginActivity.start(mContext);
                    finish();
                }
            });
        });
        mViewModel.getUserInfoObservable().observe(this, new Observer<Resource<UserInfo>>() {
            @Override
            public void onChanged(Resource<UserInfo> userInfoResource) {
                userInfoResource.handler(new OnCallback<UserInfo>(false,true) {
                    @Override
                    public void onSuccess(UserInfo data) {
                        AirConfig.get().updateUserInfo(data);
                        MainActivity.start(SplashActivity.this);
                        finish();
                    }

                });
            }
        });
    }
}
